package xyz.ag.DAO.impl;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import xyz.ag.Beans.User;
import xyz.ag.DAO.UserDAOInterface;
import xyz.ag.utils.c3p0utils;

public class UserDAOInterfaceImpl implements UserDAOInterface {

	@Override
	/**
	 * 用户登录用的方法 
	 * u是一个用户对象
	 * 修正 这里不需要返回太多的信息 只要合适是否正确的密码即可  返回boolean 2019年12月7日16:05:05
	 */
	public boolean UserLogin(User u) {
		Connection conn = c3p0utils.GetConnection();
		try {
			PreparedStatement ps= conn.prepareStatement("select * FROM user where USERname=? and userPASSWORD = password(?)");
			ps.setString(1, u.getUserName());
			ps.setString(2, u.getUserPassword());
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				if(rs.getString("username")!=null) return true;
			}
			c3p0utils.closeconn(rs, ps, conn);
		} catch (SQLException e) {
			System.err.println("用户登录数据库查询异常");
			e.printStackTrace();
		}
		return false;
	}

	@Override
	/**
	 * 添加用户的方法 
	 * 返回值是新用户的唯一id
	 */
	public Integer createNewUser(User nuser) {
		c3p0utils.executupdate("insert INTO user(userName,userPassword,userPhoneNumber,userAddress) VALUES(?,password(?),?,?)",
				nuser.getUserName(),nuser.getUserPassword(),nuser.getUserPhoneNumber(),nuser.getUserAddress());	
		return getuserid(nuser);
	}
	
	/**
	 * 获取用户id
	 * @param user
	 */
	private static Integer getuserid(User u){
		Connection conn = c3p0utils.GetConnection();
		try {
			PreparedStatement ps= conn.prepareStatement("select userID FROM user where USERname=? and userPASSWORD = password(?)");
			ps.setString(1, u.getUserName());
			ps.setString(2, u.getUserPassword());
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				if(rs.getString("userID")!=null) 
					return rs.getInt("userID");
			}
			c3p0utils.closeconn(rs, ps, conn);
		} catch (SQLException e) {
			System.err.println("用户登录数据库查询异常");
			e.printStackTrace();
		}
		return 0;
	}

	
	/**
	 * 返回一个全信息的User对象
	 */
	@Override
	public User getAlluesrMessageByUser(User user) {
		System.out.println(user.getUserName());
		Connection conn = c3p0utils.GetConnection();
		try {
			PreparedStatement ps= conn.prepareStatement("select userName,userID,userPhoneNumber,userAddress,userAccount_ID FROM user where USERname=? and userPASSWORD = password(?)");
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getUserPassword());
			ResultSet rs = ps.executeQuery();
			User auser = null;
			while(rs.next()){
			 auser  = new User.Builder().userName(rs.getString("userName")).userID(rs.getInt("userID"))
					.userAddress(rs.getString("userPhoneNumber")).userAddress("userAddress").userAccount_ID(rs.getInt("userAccount_ID")).build();
					
			}
			c3p0utils.closeconn(rs, ps, conn);
			return auser;
			
		} catch (SQLException e) {
			System.err.println("用户登录数据库查询异常");
			e.printStackTrace();
		}
	
		return null;
	}

}
